<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use GuzzleHttp\Client;
use GuzzleHttp\Promise;

/**
 * 2020-02-08
 * 这是从pepperjam获取数据判断每天接口新数据
 * 重复数据会被排除在外
 */
class Pj extends Command
{
    protected $signature = 'pj';
    protected $description = 'pepperjam数据源判断每天新进的卡券数量';
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->info('*********************program start***********************');
        
        //mongo驱动定义
        $manager = new \MongoDB\Driver\Manager("mongodb://localhost:27017");

        //查询数据库中已存在的数据id
        $filter = [];
        $options = [
            'projection' => [
                'id' => 1,
                '_id'=>0
            ]
        ];

        // 查询数据
        $query = new \MongoDB\Driver\Query($filter, $options);
        $cursor = $manager->executeQuery('local.pj', $query);
        
        $ids=[];
        foreach ($cursor as $key => $value) {
            $value=(array)$value;
            $ids[]=$value['id'];
        }

        //定义参数对接口数据进行请求
        $base_url='https://api.pepperjamnetwork.com/20120402/publisher/creative/coupon?apiKey=8d5e1e4f9c40eb7f033966d2db418d4d13dc277c7fffaae7cd4ddbf417ac42e0&format=json&page=';

        $client=new Client();
        $response = $client->request('GET',$base_url.'1');
        $res_data=json_decode($response->getBody()->read(120000000),true);
        
        //总数据
        $total_data=[];

        //查询总页数 并把第一页的数据放到总数据中
        $res_page=$res_data['meta']['pagination']['total_pages'];
 
        for ($i=1; $i <=$res_page ; $i++) { 
            $response = $client->request('GET',$base_url.$i);
            $res_data=json_decode($response->getBody()->read(12000000),true);

            //处理待插入的数据
            $to_insert_data=[];
            foreach ($res_data['data'] as $key => $value) {
                if(!in_array($value['id'],$ids)){
                    $value['create_time']=date('Y-m-d');
                    $to_insert_data[]=$value;
                }
            }
            //数据入库操作
            if($to_insert_data){
                $bulk = new \MongoDB\Driver\BulkWrite;
                foreach ($to_insert_data as $key => $value) {
                    $bulk->insert($value); 
                }
                $result=$manager->executeBulkWrite('local.pj', $bulk);
                $this->line('data is saved to database');
            }else{
                $this->line('same data have out');
            }
        }

        $this->info('**********************program stop***********************');
    }
}
